new Vue({
    el:"#chat",
    template:"<div class='col-md-6'>" +
        "<hr /><br />\n" +
        "<textarea id='message' style='width:100%;height:450px;font-size:12px' disabled='disabled'></textarea>" +
        "<input id=\"text\" type=\"text\" />" +
        "<button @click=\"send\">发送消息</button>" +
        "<hr />" +
        "</div>",

    methods:{
        conectWebSocket(){
            const that = this;
            var url = "localhost:9898";
            var groupname = "1265885645134430209";
            var username = "小吕";


            //登录
            let postData = {username:username,password:"654321"};
            axios.post("http://"+url+"/api/user/login",Qs.stringify(postData),{
                header:{
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            }
        })
                .then(response => {
                    // post 成功，知response.data 为返道回的数据
                    console.log(response.data)
                })
                .catch(error => {
                    // 请求内失败容
                    console.log(error)
                });

            //判断当前浏览器是否支持WebSocket
            if ('WebSocket'in window) {
                websocket = new WebSocket("ws://"+url+"/websocket/"+groupname+"/"+username);
                that.setMessageInnerHTML("正在连接......");
            } else {
                alert('当前浏览器不支持WebSocket');
            }
            //连接发生错误的回调方法
            websocket.onerror = function() {
                that.setMessageInnerHTML("与聊天室连接失败！请检查是否登录，如果登录了还能看到这段文字请检查网络连接！也可能是服务器出错请耐心等待修复！");
            };
            //连接成功建立的回调方法
            websocket.onopen = function(event) {

                that.setMessageInnerHTML("与服务器连接成功！");
            }
            //接收到消息的回调方法
            websocket.onmessage = function(event) {
                that.setMessageInnerHTML(event.data);
            }
            //连接关闭的回调方法
            websocket.onclose = function() {
                that.setMessageInnerHTML("连接关闭！");
            }
            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function() {
                websocket.close();
            }
        },
        //将消息显示在网页上
        setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '\n';
        },
        //关闭连接
        closeWebSocket() {
            websocket.close();
        },
        //发送消息
        send() {
            var message = document.getElementById('text').value;
            if(message==""){
            }else{
                websocket.send(message);
                document.getElementById("text").value="";
            }
        }
    },
    mounted(){
        this.conectWebSocket();
    }
})
